
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>装饰器 · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.3">
        
        
        
    
    <link rel="stylesheet" href="../../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="function.html" />
    
    
    <link rel="prev" href="../package.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../../">
            
                <a href="../../">
            
                    
                    基本介绍
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../basic.html">
            
                <a href="../basic.html">
            
                    
                    基础知识
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="../package.html">
            
                <a href="../package.html">
            
                    
                    包的概念
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.4" data-path="decorator.html">
            
                <a href="decorator.html">
            
                    
                    装饰器
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.1" data-path="function.html">
            
                <a href="function.html">
            
                    
                    函数装饰器
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.2" data-path="class.md">
            
                <span>
            
                    
                    类装饰器
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="../class/inner_class.html">
            
                <a href="../class/inner_class.html">
            
                    
                    内部类
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="../class/super.html">
            
                <a href="../class/super.html">
            
                    
                    super函数
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="../class/multiple_inheritance.html">
            
                <a href="../class/multiple_inheritance.html">
            
                    
                    类的多继承
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="../class/overwrite.html">
            
                <a href="../class/overwrite.html">
            
                    
                    类方法的重写
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="../class/multiple inheritance.md">
            
                <span>
            
                    
                    多态
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="../exception.html">
            
                <a href="../exception.html">
            
                    
                    详细了解异常的处理
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.11" data-path="../thread/treading.html">
            
                <a href="../thread/treading.html">
            
                    
                    多线程
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.12" data-path="../thread/lock.html">
            
                <a href="../thread/lock.html">
            
                    
                    线程锁
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.13" data-path="../datetime/time.html">
            
                <a href="../datetime/time.html">
            
                    
                    time模块
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.14" data-path="../datetime/timetuple.html">
            
                <a href="../datetime/timetuple.html">
            
                    
                    时间元组
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.15" data-path="../datetime/calendar.html">
            
                <a href="../datetime/calendar.html">
            
                    
                    calendar模块
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.16" data-path="../datetime/datetime.html">
            
                <a href="../datetime/datetime.html">
            
                    
                    datetime模块
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.17" data-path="../django/api.html">
            
                <a href="../django/api.html">
            
                    
                    接口
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.18" data-path="../django/front_end_and_back_end.html">
            
                <a href="../django/front_end_and_back_end.html">
            
                    
                    Django前后端分离
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.19" data-path="../django/template.html">
            
                <a href="../django/template.html">
            
                    
                    Django模板语言
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.20" data-path="../django/uwsgi.html">
            
                <a href="../django/uwsgi.html">
            
                    
                    uwsgi部署Django
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.21" data-path="../django/gunicorn.html">
            
                <a href="../django/gunicorn.html">
            
                    
                    gunicorn部署Django
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.22" data-path="../django/nginx.html">
            
                <a href="../django/nginx.html">
            
                    
                    Nginx的使用
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.23" data-path="../others/recursion.html">
            
                <a href="../others/recursion.html">
            
                    
                    递归
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.24" data-path="../others/hash.html">
            
                <a href="../others/hash.html">
            
                    
                    哈希
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.25" data-path="../others/bit_operation.html">
            
                <a href="../others/bit_operation.html">
            
                    
                    位运算
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href="../.." >装饰器</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="&#x88C5;&#x9970;&#x5668;">&#x88C5;&#x9970;&#x5668;</h1>
<h2 id="&#x51FD;&#x6570;&#x88C5;&#x9970;&#x5668;">&#x51FD;&#x6570;&#x88C5;&#x9970;&#x5668;</h2>
<pre><code class="lang-Python"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">login_required</span><span class="hljs-params">(f)</span>:</span>
    <span class="hljs-comment"># @wraps(f)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_verify</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
        <span class="hljs-string">&quot;&quot;&quot;&#x8FD9;&#x4E2A;&#x662F;&#x4FEE;&#x9970;&#x51FD;&#x6570;&quot;&quot;&quot;</span>

        print(<span class="hljs-string">&quot;&#x5982;&#x679C;&#x9A8C;&#x8BC1;&#x5931;&#x8D25;&#xFF0C;&#x5219;return&#x76F8;&#x5E94;&#x7684;&#x4FE1;&#x606F;&#xFF0C;&#x4E0B;&#x9762;&#x7684;f&#x51FD;&#x6570;&#x4E0D;&#x518D;&#x6267;&#x884C;&#x3002;&quot;</span>)
        print(<span class="hljs-string">&quot;&#x5982;&#x679C;&#x9A8C;&#x8BC1;&#x901A;&#x8FC7;&#xFF0C;&#x5219;return f&quot;</span>)
        <span class="hljs-keyword">return</span> f(<span class="hljs-string">&quot;aaa&quot;</span>, *args, **kwargs)
    <span class="hljs-keyword">return</span> _verify


<span class="hljs-meta">@login_required</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_task</span><span class="hljs-params">(a)</span>:</span>
    <span class="hljs-string">&quot;&quot;&quot;&#x8FD9;&#x4E2A;&#x662F;&#x88AB;&#x4FEE;&#x9970;&#x7684;&#x51FD;&#x6570;&quot;&quot;&quot;</span>
    print(a)
    print(<span class="hljs-string">&apos;create_task&apos;</span>)


print(create_task.__doc__)  <span class="hljs-comment"># &#x8F93;&#x51FA;`&#x8FD9;&#x4E2A;&#x662F;&#x88AB;&#x4FEE;&#x9970;&#x7684;&#x51FD;&#x6570;`</span>
print(create_task.__name__)  <span class="hljs-comment"># &#x8F93;&#x51FA;`create_task`</span>
create_task()
</code></pre>
<p>wraps:&#x5C06; <strong>&#x88AB;&#x4FEE;&#x9970;&#x7684;&#x51FD;&#x6570;(</strong>create_task<strong>)</strong> &#x7684;&#x4E00;&#x4E9B;&#x5C5E;&#x6027;&#x503C;&#x8D4B;&#x503C;&#x7ED9; <strong>&#x4FEE;&#x9970;&#x5668;&#x51FD;&#x6570;(</strong>login_required<strong>)</strong> &#xFF0C;&#x6700;&#x7EC8;&#x8BA9;&#x5C5E;&#x6027;&#x7684;&#x663E;&#x793A;&#x66F4;&#x7B26;&#x5408;&#x6211;&#x4EEC;&#x7684;&#x76F4;&#x89C9;&#x3002;</p>
<h2 id="&#x88C5;&#x9970;&#x5668;&#x8FD8;&#x53EF;&#x4EE5;&#x88C5;&#x9970;&#x7C7B;&#x54E6;">&#x88C5;&#x9970;&#x5668;&#x8FD8;&#x53EF;&#x4EE5;&#x88C5;&#x9970;&#x7C7B;&#x54E6;</h2>
<pre><code class="lang-Python"><span class="hljs-comment"># &#x5B9A;&#x4E49;</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">singleton</span><span class="hljs-params">(cls)</span>:</span>
    cls.obj = <span class="hljs-keyword">None</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_obj</span><span class="hljs-params">(*args,**kwargs)</span>:</span>
        <span class="hljs-keyword">if</span> cls.obj <span class="hljs-keyword">is</span> <span class="hljs-keyword">None</span>:
            cls.obj = cls(*args,**kwargs)
        <span class="hljs-keyword">return</span> cls.obj
    <span class="hljs-keyword">return</span> create_obj
<span class="hljs-comment"># &#x4F7F;&#x7528;</span>
<span class="hljs-meta">@singleton</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self,value)</span>:</span>
        self.value = value

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span><span class="hljs-params">(self)</span>:</span>
        <span class="hljs-keyword">return</span> self.value
<span class="hljs-comment"># &#x6D4B;&#x8BD5;</span>
print(A(<span class="hljs-string">&apos;a&apos;</span>))  <span class="hljs-comment"># &#x8F93;&#x51FA;a</span>
print(A(<span class="hljs-string">&apos;b&apos;</span>))  <span class="hljs-comment"># &#x8F93;&#x51FA;a</span>
</code></pre>
<p>&#x4E3A;&#x4EFB;&#x4F55;&#x7C7B;&#x6DFB;&#x52A0;id&#x5C5E;&#x6027;</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add_id</span><span class="hljs-params">(cls)</span>:</span>

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddId</span><span class="hljs-params">(cls)</span>:</span>

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, id, *args, **kargs)</span>:</span>
            super(AddId, self).__init__(*args, **kargs)
            self.__id = id

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_id</span><span class="hljs-params">(self)</span>:</span>
            <span class="hljs-keyword">return</span> self.__id

    <span class="hljs-keyword">return</span> AddId

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>:</span>
    <span class="hljs-keyword">pass</span>

f = add_id(Foo)
print(dir(f))
</code></pre>
<h3 id="&#x7C7B;&#x4E5F;&#x53EF;&#x4EE5;&#x505A;&#x6210;&#x88C5;&#x9970;&#x5668;&#x54E6;">&#x7C7B;&#x4E5F;&#x53EF;&#x4EE5;&#x505A;&#x6210;&#x88C5;&#x9970;&#x5668;&#x54E6;</h3>
<pre><code class="lang-Python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dec</span><span class="hljs-params">(object)</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, msg)</span>:</span>
        self.msg = msg

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self, klass)</span>:</span>
        old_foo = klass.foo
        msg = self.msg
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorated_foo</span><span class="hljs-params">(self, *args, **kwargs)</span>:</span>
            print(<span class="hljs-string">&apos;@decorator pre %s&apos;</span> % msg)
            old_foo(self, *args, **kwargs)
            print(<span class="hljs-string">&apos;@decorator post %s&apos;</span> % msg)
        klass.foo = decorated_foo
        <span class="hljs-keyword">return</span> klass
</code></pre>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">cache</span><span class="hljs-params">(func)</span>:</span>
    data = {}
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
        key = f<span class="hljs-string">&apos;{func.__name__}-{str(args)}-{str(kwargs)})&apos;</span>
        <span class="hljs-keyword">if</span> key <span class="hljs-keyword">in</span> data:
            result = data.get(key)
            print(<span class="hljs-string">&apos;cached&apos;</span>)
        <span class="hljs-keyword">else</span>:
            result = func(*args, **kwargs)
            data[key] = result
            print(<span class="hljs-string">&apos;calculated&apos;</span>)
        <span class="hljs-keyword">return</span> result
    <span class="hljs-keyword">return</span> wrapper
</code></pre>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cache</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, func)</span>:</span>
        self.func = func
        self.data = {}

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self, *args, **kwargs)</span>:</span>
        func = self.func
        data = self.data
        key = f<span class="hljs-string">&apos;{func.__name__}-{str(args)}-{str(kwargs)})&apos;</span>
        <span class="hljs-keyword">if</span> key <span class="hljs-keyword">in</span> data:
            result = data.get(key)
            print(<span class="hljs-string">&apos;cached&apos;</span>)
        <span class="hljs-keyword">else</span>:
            result = func(*args, **kwargs)
            data[key] = result
            print(<span class="hljs-string">&apos;calculated&apos;</span>)
        <span class="hljs-keyword">return</span> result
</code></pre>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span><span class="hljs-params">(object)</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self,func)</span>:</span>
        print(<span class="hljs-string">&apos;&#x5B9A;&#x4E49;&#x521D;&#x59CB;&#x5316;&#x51FD;&#x6570;&apos;</span>)
        print(<span class="hljs-string">&apos;func name is %s&apos;</span>%func.__name__)
        self.__func = func

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self)</span>:</span>
        print(<span class="hljs-string">&apos;call &#x65B9;&#x6CD5;&#x4F5C;&#x4E3A;&#x88C5;&#x8D77;&#x4E2D;&#x7684;&#x529F;&#x80FD;&apos;</span>)
        self.__func()
        print(<span class="hljs-string">&apos;&#x589E;&#x52A0;&#x7684;&#x529F;&#x80FD;2&apos;</span>)

<span class="hljs-meta">@A</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">B</span><span class="hljs-params">()</span>:</span>
    print(<span class="hljs-string">&apos;&#x8FD9;&#x4E2A;&#x662F;B&#x662F;&#x539F;&#x51FD;&#x6570;&apos;</span>)

<span class="hljs-comment"># A(B)</span>
B()
</code></pre>
<h2 id="&#x6848;&#x4F8B;&#x4E00;&#xFF1A;">&#x6848;&#x4F8B;&#x4E00;&#xFF1A;</h2>
<pre><code class="lang-python"><span class="hljs-comment"># To expand on the __get__ approach. This can be generalized into a decorator decorator.</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_MethodDecoratorAdaptor</span><span class="hljs-params">(object)</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, decorator, func)</span>:</span>
        self.decorator = decorator
        self.func = func
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self, *args, **kwargs)</span>:</span>
        <span class="hljs-keyword">return</span> self.decorator(self.func)(*args, **kwargs)
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__get__</span><span class="hljs-params">(self, instance, owner)</span>:</span>
        <span class="hljs-keyword">return</span> self.decorator(self.func.__get__(instance, owner))

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">auto_adapt_to_methods</span><span class="hljs-params">(decorator)</span>:</span>
    <span class="hljs-string">&quot;&quot;&quot;Allows you to use the same decorator on methods and functions,
    hiding the self argument from the decorator.&quot;&quot;&quot;</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">adapt</span><span class="hljs-params">(func)</span>:</span>
        <span class="hljs-keyword">return</span> _MethodDecoratorAdaptor(decorator, func)
    <span class="hljs-keyword">return</span> adapt

<span class="hljs-comment"># In this way you can just make your decorator automatically adapt to the conditions it is used in.</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">allowed</span><span class="hljs-params">(*allowed_methods)</span>:</span>
<span class="hljs-meta">    @auto_adapt_to_methods</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span><span class="hljs-params">(func)</span>:</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapped</span><span class="hljs-params">(request)</span>:</span>
            <span class="hljs-keyword">if</span> request <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> allowed_methods:
                <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">&quot;Invalid method %s&quot;</span> % request)
            <span class="hljs-keyword">return</span> func(request)
        <span class="hljs-keyword">return</span> wrapped
    <span class="hljs-keyword">return</span> wrapper
<span class="hljs-comment"># Notice that the wrapper function is called on all function calls, so don&apos;t do anything expensive there.</span>
<span class="hljs-comment"># Usage of the decorator:</span>


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span><span class="hljs-params">(object)</span>:</span>
<span class="hljs-meta">    @allowed(&apos;GET&apos;, &apos;POST&apos;)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">do</span><span class="hljs-params">(self, request)</span>:</span>
        <span class="hljs-keyword">print</span> <span class="hljs-string">&quot;Request %s on %s&quot;</span> % (request, self)

<span class="hljs-meta">@allowed(&apos;GET&apos;)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">do</span><span class="hljs-params">(request)</span>:</span>
    <span class="hljs-keyword">print</span> <span class="hljs-string">&quot;Plain request %s&quot;</span> % request

Foo().do(<span class="hljs-string">&apos;GET&apos;</span>)  <span class="hljs-comment"># Works</span>
Foo().do(<span class="hljs-string">&apos;POST&apos;</span>) <span class="hljs-comment"># Raises</span>
</code></pre>
<p>&#x53C2;&#x8003;&#x8D44;&#x6599;&#xFF1A;<a href="https://stackoverflow.com/questions/1288498/using-the-same-decorator-with-arguments-with-functions-and-methods" target="_blank">https://stackoverflow.com/questions/1288498/using-the-same-decorator-with-arguments-with-functions-and-methods</a></p>
<h2 id="&#x6848;&#x4F8B;&#x4E8C;&#xFF1A;">&#x6848;&#x4F8B;&#x4E8C;&#xFF1A;</h2>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> functools
<span class="hljs-keyword">import</span> time
<span class="hljs-keyword">import</span> logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">call_logger</span><span class="hljs-params">(object)</span>:</span>
    <span class="hljs-string">&quot;&quot;&quot;
    Decorator class to log calls on functions or class methods,
    e.g..
        @call_logger
        def my_function():
       class MyClass(object):         
            @call_logger
            def my_method(self):
    &quot;&quot;&quot;</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, func)</span>:</span>
        self._func = func 
        self._wrapped = <span class="hljs-keyword">None</span>
        self._obj = <span class="hljs-keyword">None</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self, *args, **kwags)</span>:</span>
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> self._wrapped:
            <span class="hljs-keyword">if</span> self._obj:
                self._wrapped = self._wrap_method(self._func)
                self._wrapped = functools.partial(self._wrapped, self._obj)
            <span class="hljs-keyword">else</span>:
                self._wrapped = self._wrap_function(self._func)
        <span class="hljs-keyword">return</span> self._wrapped(*args, **kwags)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__get__</span><span class="hljs-params">(self, obj, type=None)</span>:</span>
        self._obj = obj
        <span class="hljs-keyword">return</span> self

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_wrap_function</span><span class="hljs-params">(self, function)</span>:</span>
        <span class="hljs-string">&quot;&quot;&quot;
        Perform the decorator wrapping for a regular function.
        &quot;&quot;&quot;</span>
<span class="hljs-meta">        @functools.wraps(function)</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner</span><span class="hljs-params">(*args, **kwags)</span>:</span>
            <span class="hljs-string">&quot;&quot;&quot;
            Implementation of the wraped function.
            &quot;&quot;&quot;</span>
            started = time.time()
            exc_name = <span class="hljs-keyword">None</span>
            result = <span class="hljs-keyword">None</span>
            <span class="hljs-keyword">try</span>:
                result = function(*args, **kwags)
            <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> ex:
                exc_name = type(ex).__name__
                <span class="hljs-keyword">raise</span>
            <span class="hljs-keyword">finally</span>:
                _log_it(started, function, result, exc_name)
            <span class="hljs-keyword">return</span> result
        <span class="hljs-keyword">return</span> inner

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_wrap_method</span><span class="hljs-params">(self, method)</span>:</span>
        <span class="hljs-string">&quot;&quot;&quot;
        Perform the decorator wrapping for a class method.
        &quot;&quot;&quot;</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner</span><span class="hljs-params">(self, *args, **kwags)</span>:</span>
            <span class="hljs-string">&quot;&quot;&quot;
            Implementation of the wrapped function.
            &quot;&quot;&quot;</span>
            started = time.time()
            exc_name = <span class="hljs-keyword">None</span>
            result = <span class="hljs-keyword">None</span>
            <span class="hljs-keyword">try</span>:
                result = method(self, *args, **kwags)
            <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> ex:
                exc_name = type(ex).__name__
                <span class="hljs-keyword">raise</span>
            <span class="hljs-keyword">finally</span>:
                _log_it(started, method, result, exc_name)
        <span class="hljs-keyword">return</span> inner


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_log_it</span><span class="hljs-params">(started, method, result, exc_name)</span>:</span>
    finished = time.time()
    elapsed = (finished - started) * <span class="hljs-number">1000</span>
    modname, methname = _get_caller_info(method)
    logging.debug(<span class="hljs-string">&quot;%s %s takes %s ms&quot;</span>, modname, methname, elapsed)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_get_caller_info</span><span class="hljs-params">(method)</span>:</span>
    modname = method.__module__
    methname = method.__name__
    <span class="hljs-keyword">return</span> modname, methname

<span class="hljs-meta">@call_logger</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test</span><span class="hljs-params">()</span>:</span>
    <span class="hljs-keyword">print</span> <span class="hljs-string">&apos;test function&apos;</span>
    time.sleep(<span class="hljs-number">1</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">True</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span><span class="hljs-params">(object)</span>:</span>

<span class="hljs-meta">    @call_logger</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_method</span><span class="hljs-params">(self)</span>:</span>
        time.sleep(<span class="hljs-number">1</span>)
        <span class="hljs-keyword">print</span> <span class="hljs-string">&quot;test method&quot;</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&quot;__main__&quot;</span>:
    test()
    test_obj = MyClass()
    test_obj.test_method()

&#x4F5C;&#x8005;&#xFF1A;&#x4F0D;&#x53EA;&#x868A;
&#x94FE;&#x63A5;&#xFF1A;https://www.jianshu.com/p/d1514cd7275d
&#x4F86;&#x6E90;&#xFF1A;&#x7B80;&#x4E66;
&#x7B80;&#x4E66;&#x8457;&#x4F5C;&#x6743;&#x5F52;&#x4F5C;&#x8005;&#x6240;&#x6709;&#xFF0C;&#x4EFB;&#x4F55;&#x5F62;&#x5F0F;&#x7684;&#x8F6C;&#x8F7D;&#x90FD;&#x8BF7;&#x8054;&#x7CFB;&#x4F5C;&#x8005;&#x83B7;&#x5F97;&#x6388;&#x6743;&#x5E76;&#x6CE8;&#x660E;&#x51FA;&#x5904;&#x3002;
</code></pre>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="../package.html" class="navigation navigation-prev " aria-label="Previous page: 包的概念">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="function.html" class="navigation navigation-next " aria-label="Next page: 函数装饰器">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"装饰器","level":"1.4","depth":1,"next":{"title":"函数装饰器","level":"1.4.1","depth":2,"path":"mds/decorator/function.md","ref":"mds/decorator/function.md","articles":[]},"previous":{"title":"包的概念","level":"1.3","depth":1,"path":"mds/package.md","ref":"mds/package.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":["livereload"],"pluginsConfig":{"livereload":{},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"mds/decorator/decorator.md","mtime":"2019-02-21T15:47:02.814Z","type":"markdown"},"gitbook":{"version":"3.2.3","time":"2019-02-25T03:21:04.918Z"},"basePath":"../..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../../gitbook/gitbook.js"></script>
    <script src="../../gitbook/theme.js"></script>
    
        
        <script src="../../gitbook/gitbook-plugin-livereload/plugin.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

